package com.tuzhi.filestore.service.impl;

import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.filestore.config.FileStoreConfig;
import com.tuzhi.filestore.model.response.ErrorCode;
import com.tuzhi.filestore.model.response.Result;
import com.tuzhi.filestore.model.response.Results;
import com.tuzhi.filestore.service.FileUpLogService;
import com.tuzhi.filestore.utils.EmptyUtils;
import com.tuzhi.filestore.utils.UuidUtils;
import com.tuzhi.vo.bill.FileUpLogVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Paths;
import java.util.Date;

/**
 * <p>
 * 文件上传下载 服务实现类
 * </p>
 *
 * @author LEON
 * @since 2020-05-29
 */
@Slf4j
@Service
public class FileUpLogServiceImpl implements FileUpLogService {


    @Autowired
    FileStoreConfig fileStoreConfig;

    private String savePath;
    private String confFilePath;

    final static long MAX_SIZE = 536870912L;


    @PostConstruct
    public void init() {
        savePath = fileStoreConfig.getSavePath();
        confFilePath = fileStoreConfig.getConfFilePath();
    }

    /**
     * 上传文件 至服务器，并返回上传文件后的文件日志信息
     * 文件大小，文件名，新的文件名，保存路径
     *
     * @param file
     * @return
     */
    @Override
    public Result<FileUpLogVo> upLoadOrderModel(MultipartFile file) {

        String ncDir = DateFormatUtils.format(new Date(), "yyyyMM");

        String savePathNew = Paths.get(savePath, ncDir).toString();

        Result<String> ret = uploadFile(file, savePathNew, true, null);
        if (ret.isSuccess()) {
            // 保存文件信息
            FileUpLogVo fileUpLogEntity = new FileUpLogVo();
            fileUpLogEntity.setFileName(ret.getData());
            fileUpLogEntity.setOriginalFileName(file.getOriginalFilename());
            //fileUpLogEntity.setCreatedTime(new Date());
            fileUpLogEntity.setFileSize(file.getSize());
            fileUpLogEntity.setFtpDir(ncDir);
            fileUpLogEntity.setSource("CUSTOMER");
            Result<FileUpLogVo> result = Results.newSuccessResult(fileUpLogEntity);
            return result;
        }
        return Results.newFailResult(ret.getErrorCode(), ret.getDescription());

    }


    /**
     * 上传文件 到服务器
     *
     * @param multipartFile  文件信息
     * @param savePath       保存的文件路径
     * @param reName         如果重命名，指定了 customFileName 不为空，用customFileName，为空，生成UUID 的名
     * @param customFileName 调用者指定文件名， ,且此字段不为空
     * @return
     */
    private Result<String> uploadFile(MultipartFile multipartFile, String savePath, boolean reName, String customFileName) {
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            // 文件名非空校验
            if (EmptyUtils.basicIsEmpty(originalFilename)) {
                return Results.newFailResult(ErrorCode.FILE_ERROR, "文件名不能为空");
            }
            // 大文件判定，getSize获取的大小是byte，转KB:/1024,转MB:/1024/1024,
            if (multipartFile.getSize() > MAX_SIZE) {
                log.error("multipartFile.getSize()：{}", multipartFile.getSize());
                return Results.newFailResult(ErrorCode.FILE_ERROR, "文件过大，超过512M");
            }
            String extName = FilenameUtils.getExtension(originalFilename);
            // 生成新文件名
            String newName = originalFilename;
            if (reName) {
                if (StringUtils.isNotEmpty(customFileName)) {
                    newName = customFileName;
                } else {
                    //newName = UuidUtils.uuid() + "_" + originalFilename;
                    newName = String.format("%s.%s", UuidUtils.uuid(), extName);

                }
            }

            if (originalFilename.length() > 500) {
                throw new BusinessException(originalFilename + "文件名超长 500");
            }
            if (newName.length() > 500) {
                throw new BusinessException(newName + "文件名超长 500");
            }
            if (savePath.length() > 500) {
                throw new BusinessException(savePath + "文件保存目录超长 500");
            }

            // 重命名文件
            File newFile = new File(savePath, newName);
            // 如果该存储路径不存在则新建存储路径
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            // 文件写入
            multipartFile.transferTo(newFile);
            return Results.newSuccessResult(newName, "上传完成", null);
        } catch (Exception e) {
            log.error("上传协议文件出错", e);
            return Results.newFailResult(ErrorCode.FILE_ERROR, ExceptionUtils.getRootCauseMessage(e));

        }
    }

}
